package edu.fudan.jwxt.controller;

import edu.fudan.jwxt.annotation.Adminer;
import edu.fudan.jwxt.common.Constants;
import edu.fudan.jwxt.common.ResultBody;
import edu.fudan.jwxt.dto.CollegeDto;
import edu.fudan.jwxt.entity.College;
import edu.fudan.jwxt.entity.Major;
import edu.fudan.jwxt.service.CollegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/colleges")
public class CollegeController {
    @Autowired
    private CollegeService collegeService;


    @GetMapping
    public ResultBody CollegesListAll(){
        List<CollegeDto> collegeDtos = collegeService.listAll();

        return ResultBody.success(collegeDtos);
    }


    @GetMapping("/{collegeId}")
    public ResultBody getCollege(@PathVariable int collegeId){

        College college = collegeService.getById(collegeId);
        if (college == null)
            return ResultBody.error(Constants.CODE_600,"不存在该学院");

        return ResultBody.success(college);
    }

    //TODO: 用户权限检查
    @PostMapping("/update")
    public ResultBody updateCollege(@RequestBody College college){
        boolean flag = collegeService.updateById(college);
        if(!flag)
            return ResultBody.error(Constants.CODE_600,"不存在该学院");
        return ResultBody.success();
    }

    //TODO: 用户权限检查
    @PostMapping("/insert")
    public ResultBody insertCollege(@RequestBody College college){
        collegeService.save(college);

        return ResultBody.success();
    }

    //TODO: 用户权限检查
    @PostMapping("/inserts")
    public ResultBody insertCollegeList(@RequestBody List<College> colleges){
        collegeService.saveBatch(colleges);

        return ResultBody.success();
    }

    //TODO: 用户权限检查
    @DeleteMapping("/{collegeId}")
    public ResultBody Delete(@PathVariable int collegeId){

        boolean flag = collegeService.removeById(collegeId);
        if(flag)
            return ResultBody.success();
        else
            return ResultBody.error(Constants.CODE_600,"不存在该学院");

    }

    //TODO: 用户权限检查
    @PostMapping("/delete")
    public ResultBody DeleteList(@RequestBody List<Integer> ids){

        int failCount = 0;
        for (int id : ids){
            try {
                collegeService.removeById(id);
            }catch (Exception e){
                failCount++;
            }
        }

        if(failCount == 0)
            return ResultBody.success();
        else
            return ResultBody.error(Constants.CODE_600,"有部分学院无法删除");
    }



}
